package formula.web;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

import twork.jsf.util.TworkJsfMessageUtil;
import formula.business.model.Team;
import formula.business.repo.TeamRepository;

@SuppressWarnings("serial")
@ManagedBean
@SessionScoped
public class TeamHome implements Serializable {

	public static final String EL_NAME = "#{teamHome}";
	@ManagedProperty(value = TeamRepository.EL_NAME)
	private TeamRepository teamRepository;
	//
	private Team team;
	private Long teamId;

	/**
	 * All the logic is HERE, it is easier than a Factory Pattern, and reusable
	 */
	public Team getTeam() {
		if (team == null) {
			if ((teamId == null)) {
				team = new Team();
			} else if ((teamId != null) && (team == null)) {
				team = teamRepository.findOne(teamId);
				if (team == null) {
					throw new WebRuntimeException("not.found.by.id", teamId);
				}
			}
		}
		return team;
	}

	public void clear() {
		team = null;
		teamId = null;
	}

	public void doMerge() {
		// the id of team will be null if we are in creation mode
		Long idBeforeMerge = team.getId();
		team = teamRepository.saveAndFlush(team);
		String key = idBeforeMerge == null ? "success.create" : "success.update";
		TworkJsfMessageUtil.addMessageInfo("appMsg", key, Team.class.getSimpleName(), this.team.getName());
		this.team = null;
		this.teamId = null;
	}

	public void doDelete() {
		teamRepository.delete(team);
		//
		TworkJsfMessageUtil.addMessageInfo("appMsg", "success.delete", "Team", this.team.getName());
		this.team = null;
		this.teamId = null;
	}

	public Long getTeamId() {
		return teamId;
	}

	public void setTeamId(Long _teamId) {
		if (_teamId != null) {
			team = null;
			teamId = _teamId;
		}
	}

	public void setTeam(Team team) {
		this.team = team;
	}

	public boolean isTeamEmpty() {
		if (team == null) {
			if ((teamId == null)) {
				return true;
			}
		}
		return false;
	}

	public void setTeamRepository(TeamRepository _teamRepository) {
		teamRepository = _teamRepository;
	}
}
